/**
 * Created with IntelliJ IDEA.
 * User: Hkkkk Guo
 * Date: 2023/2/14
 * Time: 12:26
 * Description:
 */
package com.hangkai.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hangkai.reggie.common.BaseContext;
import com.hangkai.reggie.dao.OrdersDao;
import com.hangkai.reggie.domain.*;
import com.hangkai.reggie.exception.CustomException;
import com.hangkai.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;
    /**
     * 用户下单
     * @param orders
     * @return
     */
    @Override
    @Transactional
    public void submit(Orders orders) {
        //1 获得当前用户id
        Long userId = BaseContext.getCurrentId();
        //2 查询当前用户购物车数据
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqw);
        if(shoppingCartList == null || shoppingCartList.size() == 0){
            throw new CustomException("购物车为空 不能下单");
        }
        //根据用户id 查出用户信息
        User user = userService.getById(userId);
        //查出地址数据
        Long addressId = orders.getAddressBookId();
        AddressBook address = addressBookService.getById(addressId);
        if(address == null){
            throw new CustomException("地址信息有误不能下单");
        }
        //3 向订单表插入数据 一条数据
        //设置订单号
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String orderId = user.getPhone().substring(6) + time; //手机后五位 + 时间戳14位 共20位
        Long order_long = Long.valueOf(orderId);
        orders.setNumber(orderId);
        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        //设置确认时间 这里为了简便 默认与下单时间一样
        orders.setCheckoutTime(LocalDateTime.now());
        //订单状态
        orders.setStatus(2);
        //订单价格
        //******需要遍历购物车 得到价格 并计算
        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> orderDetails = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order_long);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            //AtomicInteger.multiply()要传入BigDecimal的类
            amount.getAndAdd(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //下单用户id和名字
        orders.setUserId(userId);
        orders.setUserName(user.getName());
        //收货人信息
        orders.setConsignee(address.getConsignee());
        orders.setPhone(address.getPhone());
        //收货地址
        orders.setAddress((address.getProvinceName() == null ? "" : address.getProvinceName())
                        + (address.getCityName() == null ? "" : address.getCityName())
                        + (address.getDistrictName() == null ? "" : address.getDistrictName())
                        + (address.getDetail() == null ? "" : address.getDetail()));
        //实收金额
        orders.setAmount(new BigDecimal(String.valueOf(amount)));
        this.save(orders);
        //4 向订单明细表插入数据 多条数据
        orderDetailService.saveBatch(orderDetails);
        //5 下单成功后清空购物车
        shoppingCartService.remove(lqw);
    }
}
